package com.guanzhi.validation.validator;

import com.guanzhi.validation.domain.Person;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * Spring6
 * <p> Package: com.guanzhi.validation.validator </p>
 * <p> File: PersonValidator.java </p>
 * <p> Description:  (使用接口形式 实现validation数据校验 实现接口)</p>
 * <p> Date: 2024/9/21 17:46</p>
 *
 * @author LiKai
 * @version 1.0 （代码版本）
 * @email <a href="mailto:Likai55634@aliyun.com">LiKai</a>（邮箱）
 * @date 2024/9/21 17:46
 * @since jdk1.8（jdk版本）
 */
public class PersonValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return Person.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        // 校验name,不能为空
        ValidationUtils.rejectIfEmpty(errors,"name","name.empty","name can not be empty");
        Person person = (Person) target;
        if (person.getAge() < 0) {
            errors.rejectValue("age","age.negative","age can not be negative");
        }else if (person.getAge() > 120) {
            errors.rejectValue("age","age.too.large","age can not be too large");
        }
    }
}
